package com.xiatl.cgi.server.cgi.handler;

import com.xiatl.cgi.server.cgi.CgiDataModel;
import com.xiatl.cgi.server.cgi.CgiUserModel;
import com.xiatl.cgi.server.cgi.code.RespCode;
import com.xiatl.cgi.server.cgi.exception.CgiException;
import com.xiatl.cgi.server.cgi.utils.SignUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * cgi 处理签名
 */
@Component
public class CgiSignHandler implements ICgiHandler {

    private final Logger logger = LoggerFactory.getLogger(CgiSignHandler.class);

    @Override
    public void handle(CgiDataModel dataModel) throws CgiException {
        logger.info("do CgiSignHandler...");
        // 必填参数[appKey, sign, timestamp]
        if (StringUtils.isEmpty(dataModel.getAppKey())) {
            throw new CgiException(RespCode.ERROR, "参数[appKey]不可为空");
        }
        if (StringUtils.isEmpty(dataModel.getSign())) {
            throw new CgiException(RespCode.ERROR, "参数[sign]不可为空");
        }
        if (StringUtils.isEmpty(dataModel.getTimestamp())) {
            throw new CgiException(RespCode.ERROR, "参数[timestamp]不可为空");
        }
        long second = new Date().getTime() - Long.parseLong(dataModel.getTimestamp());
        // 10分钟
        if (second > (1000 * 60 * 10)) {
            throw new CgiException(RespCode.ERROR, "请求时间超时");
        }

        // 校验appKey是否存在
        CgiUserModel cgiUserModel = this.testDB(dataModel.getAppKey());
        if (cgiUserModel == null) {
            throw new CgiException(RespCode.ERROR, "无效的[appKey]");
        }

        // 校验签名，参数&secret进行签名验证
        String paramsSign = SignUtil.sign(dataModel.getParams(), dataModel.getPath(), cgiUserModel.getAppSecret(), dataModel.getTimestamp());
        if (!paramsSign.equals(dataModel.getSign())) {
            throw new CgiException(RespCode.ERROR, "无效的[sign]");
        }
    }

    /**
     * 测试数据表用户表
     *
     * @return
     */
    private CgiUserModel testDB(String appKey) {
        List<CgiUserModel> userModelList = new ArrayList<>();
        userModelList.add(new CgiUserModel("用户1", "username1", "12345678"));
        userModelList.add(new CgiUserModel("用户1", "username2", "23456789"));
        List<CgiUserModel> collect = userModelList.stream().filter(e -> e.getAppKey().equals(appKey)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(collect)) {
            return collect.get(0);
        }
        return null;
    }

}
